import { useCallback, useState } from 'react';

export default function useUrlQueryState(initState = {}) {
  // 设置地址栏
  const combineUrl = url => window.history.pushState(null, null, url.toString());

  // url 参数同步到 state
  const matchUrlToState = state => {
    const url = new URL(window.location.href);
    const nextState = Object.keys(state).reduce((nextState, key) => {
      if (url.searchParams.has(key) && url.searchParams.get(key)) {
        return { ...nextState, [key]: url.searchParams.get(key) };
      }
      url.searchParams.set(key, state[key]);
      return { ...nextState };
    }, state);
    combineUrl(url);
    return nextState;
  };

  // state 同步到 url 参数
  const matchStateToUrl = useCallback(state => {
    const url = new URL(window.location.href);
    Object.keys(state).forEach(key => {
      url.searchParams.set(key, state[key]);
    });
    combineUrl(url);
    return state;
  }, []);

  // url state: 保持 state 和 url 同步
  const [urlState, setUrlState] = useState(matchUrlToState(initState));

  // 同步 url 和 state
  const combineUrlState = useCallback(
    state => {
      setUrlState(matchStateToUrl(state));
    },
    [matchStateToUrl],
  );

  return [urlState, combineUrlState];
}
